package com.tianyu.service.http;

import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tianyu.common.AppConstants;
import com.tianyu.service.tcp.TianyuCompanyMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.ui.ModelMap;
import org.springframework.util.DigestUtils;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;

import java.util.HashMap;
import java.util.Objects;

import static org.springframework.http.HttpMethod.*;


/**********************************
 * @author swyan
 * @description HttpRequest.java
 * @date 2024/7/29 - 17:41
 **********************************/


@Slf4j
@Component
public class HttpRequest {

    @Resource
    private AppConstants appConstants;

    public JSONObject login(TianyuCompanyMessage message) {
        JSONObject map = new JSONObject();
        long timeStamp = System.currentTimeMillis();
        map.put("accessKeyId", message.getCpAccessKey());
        map.put("encryptStr", DigestUtils.md5DigestAsHex((message.getCpAccessKey() + message.getCpAccessSecret() + timeStamp).getBytes()));
        map.put("timeStamp", timeStamp);
        try {
            final String path = appConstants.getTianyuServer().getHttpPrefix() + "/eapi/auth/getToken";
            return doRequest(path, map, new HttpHeaders(), HttpMethod.POST);
        } catch (ResourceAccessException | HttpServerErrorException.BadGateway e) {
            log.error("服务端或已关闭，拒绝连接...");
        } catch (RestClientException | IllegalArgumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    public JSONObject boxListGet(TianyuCompanyMessage message) {
        final String path = appConstants.getTianyuServer().getHttpPrefix() + appConstants.getTianyuServer().getHttpPathPrefix().getBoxListGet();
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        return doRequest(path, null, requestHeader, GET);
    }

    public JSONObject boxUpdatePost(TianyuCompanyMessage message, JSONObject requestBody) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() + appConstants.getTianyuServer().getHttpPathPrefix().getBoxUpdatePost();
        return doRequest(path, requestBody, requestHeader, HttpMethod.POST);
    }

    public JSONObject boxHistoryPost(TianyuCompanyMessage message, JSONObject requestBody) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() + appConstants.getTianyuServer().getHttpPathPrefix().getBoxHistoryPost();
        return doRequest(path, requestBody, requestHeader, HttpMethod.POST);
    }

    public JSONObject boxLiveOpenGetPrefix(TianyuCompanyMessage message, String boxSn) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() +
                appConstants.getTianyuServer().getHttpPathPrefix().getBoxLiveOpenGetPrefix() + boxSn;
        return doRequest(path, null, requestHeader, GET);
    }

    public JSONObject boxLivePullGetPrefix(TianyuCompanyMessage message, String boxSn) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() +
                appConstants.getTianyuServer().getHttpPathPrefix().getBoxLivePullGetPrefix() + boxSn;
        return doRequest(path, null, requestHeader, GET);
    }

    public JSONObject boxLiveUpdatePost(TianyuCompanyMessage message, JSONObject requestBody) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() + appConstants.getTianyuServer().getHttpPathPrefix().getBoxLiveUpdatePost();
        return doRequest(path, requestBody, requestHeader, HttpMethod.POST);
    }


    public JSONObject boxPhotosPost(TianyuCompanyMessage message, JSONObject requestBody) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() + appConstants.getTianyuServer().getHttpPathPrefix().getBoxPhotosPost();
        return doRequest(path, requestBody, requestHeader, HttpMethod.POST);
    }

    public JSONObject kmzConvertPost(TianyuCompanyMessage message, MultipartFile requestBody) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() + appConstants.getTianyuServer().getHttpPathPrefix().getKmzConvertPost();
        RestTemplate restTemplate = new RestTemplate();
        HttpEntity<MultipartFile> httpEntity = new HttpEntity<>(requestBody, requestHeader);
        return restTemplate.postForObject(path, httpEntity, JSONObject.class);
    }

    public JSONObject hangarListGet(TianyuCompanyMessage message) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() +
                appConstants.getTianyuServer().getHttpPathPrefix().getHangarListGet();
        return doRequest(path, null, requestHeader, GET);
    }

    public JSONObject hangarControlGet(TianyuCompanyMessage message, String hangarSn, String instructId) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() +
                appConstants.getTianyuServer().getHttpPathPrefix().getHangarControlGetPrefix() +
                hangarSn + "/" + instructId;
        return doRequest(path, null, requestHeader, GET);
    }

    public static void main(String[] args) {
        new HttpRequest().lastLineGet2(TianyuCompanyMessage.builder()
                .companyId(17232)
                .token("4SSEFI8Bxww5yESCdqf7MwuW9pvRBHTa8JePhfTGpyk")
                .build(), "M26220230415013");
    }

    private static final JSONObject emptyRequestBody = new JSONObject();

    public JSONObject lastLineGet2(TianyuCompanyMessage message, String hangarSn) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = "http://127.0.0.1:17680/api/v1.0/test";

        emptyRequestBody.put("deviceSn", "");
        emptyRequestBody.put("templateId", "");

        return doRequest(path, emptyRequestBody, requestHeader, POST);
    }

    public JSONObject lastLineGet(TianyuCompanyMessage message, String hangarSn) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() + appConstants.getTianyuServer().getHttpPathPrefix().getLastLineGetPrefix() + hangarSn;
        return doRequest(path, null, requestHeader, GET);
    }

    /**
     * @param message
     * @param hangarSn
     * @param command  1 航线暂停 2 航线恢复
     * @return
     */
    public JSONObject lineControl(TianyuCompanyMessage message, String hangarSn, Integer command) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() + appConstants.getTianyuServer().getHttpPathPrefix().getLineControlGetPrefix() + hangarSn + "/" + command;
        return doRequest(path, null, requestHeader, GET);
    }

    public JSONObject hangarLinePost(TianyuCompanyMessage message, JSONObject requestBody) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() +
                appConstants.getTianyuServer().getHttpPathPrefix().getHangarLinePost();
        return doRequest(path, requestBody, requestHeader, HttpMethod.POST);
    }

    public JSONObject hangarLineExecutePost(TianyuCompanyMessage message, JSONObject requestBody) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() +
                appConstants.getTianyuServer().getHttpPathPrefix().getLineTemplateExecutePost();
        return doRequest(path, requestBody, requestHeader, HttpMethod.POST);
    }

    public JSONObject hangarUavTakeoffPost(TianyuCompanyMessage message, JSONObject requestBody) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() +
                appConstants.getTianyuServer().getHttpPathPrefix().getHangarUavTakeoffPost();
        return doRequest(path, requestBody, requestHeader, HttpMethod.POST);
    }

    public JSONObject hangarUpdatePost(TianyuCompanyMessage message, JSONObject requestBody) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() +
                appConstants.getTianyuServer().getHttpPathPrefix().getHangarUpdatePost();
        return doRequest(path, requestBody, requestHeader, HttpMethod.POST);
    }

    /**
     * @param message  鉴权信息
     * @param hangarSn 机场SN
     * @param type     rtmp | rtc | flv
     * @return
     */
    public JSONObject hangarInVideoGet(TianyuCompanyMessage message, String hangarSn, String type) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() +
                appConstants.getTianyuServer().getHttpPathPrefix().getHangarInVideoGetPrefix() + hangarSn + "/" + type;
        return doRequest(path, null, requestHeader, GET);
    }

    public JSONObject hangarOutVideoGet(TianyuCompanyMessage message, String hangarSn, String type) {
        final HttpHeaders requestHeader = new HttpHeaders();
        requestHeader.add("x-cid", String.valueOf(message.getCompanyId()));
        requestHeader.add("x-token", message.getToken());
        final String path = appConstants.getTianyuServer().getHttpPrefix() +
                appConstants.getTianyuServer().getHttpPathPrefix().getHangarOutVideoGetPrefix() + hangarSn + "/" + type;
        return doRequest(path, null, requestHeader, GET);
    }

    public static JSONObject doRequest(String path, JSONObject requestBody, HttpHeaders requestHeader, HttpMethod method) {
        log.info("TY-HTTP[{}] PATH: {} | params: {}", method, path, requestBody == null ? "-" : requestBody.toJSONString());
        RestTemplate restTemplate = new RestTemplate();
        try {
            if (method.equals(GET)) {
                HttpEntity<JSONObject> requestEntity = new HttpEntity<>(requestBody, requestHeader);
                final ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(path, GET, requestEntity, JSONObject.class);
                return responseEntity.getBody();
            } else if (method.equals(POST)) {
                HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(
                        requestBody != null ? requestBody : new JSONObject(), requestHeader);
                return restTemplate.postForObject(path, httpEntity, JSONObject.class);
            } else if (method.equals(DELETE)) {
                HttpEntity<JSONObject> requestEntity = new HttpEntity<>(requestBody, requestHeader);
                final ResponseEntity<JSONObject> responseEntity = restTemplate.exchange(path, DELETE, requestEntity, JSONObject.class);
                return responseEntity.getBody();
            }
        } catch (ResourceAccessException | HttpServerErrorException.BadGateway e) {
            log.error("服务端或已关闭，拒绝连接...");
        } catch (RestClientException | IllegalArgumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Http登录云平台获取 userId utoken 作为获取云盒列表的请求头字段
     *
     * @param boxHost         访问主机
     * @param accessKeyId     访问Key
     * @param accessKeySecret 访问密钥
     * @return
     */
    public static JSONObject cloudPlatformCompanyLogin(String boxHost, String accessKeyId, String accessKeySecret) {
        HashMap<String, Object> map = new HashMap<>(3);
        long timeStamp = System.currentTimeMillis();
        map.put("accessKeyId", accessKeyId);
        map.put("encryptStr", DigestUtils.md5DigestAsHex((accessKeyId + accessKeySecret + timeStamp).getBytes()));
        map.put("timeStamp", timeStamp);
        HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(new JSONObject());
        RestTemplate restTemplate = new RestTemplate();
        try {
            return restTemplate.postForObject(boxHost + "/eapi/auth/getToken", httpEntity, JSONObject.class);
        } catch (ResourceAccessException | HttpServerErrorException.BadGateway e) {
            log.error("服务端或已关闭，拒绝连接...");
        } catch (RestClientException | IllegalArgumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Http登录云平台获取 userId utoken 作为获取云盒列表的请求头字段
     *
     * @param boxHost
     * @param name
     * @param password
     * @return
     */
    public static ModelMap cloudPlatformUserLogin(String boxHost, String name, String password) {
        HashMap<String, Object> map = new HashMap<>(2);
        map.put("accountNumber", name);
        map.put("accountCode", password);
        HttpHeaders httpHeaders = new HttpHeaders();
        HttpEntity<HashMap<String, Object>> httpEntity = new HttpEntity<>(map, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ModelMap result = restTemplate.postForObject(boxHost + "/api/client/login", httpEntity, ModelMap.class);
        ModelMap resultMap = new ModelMap();
        resultMap.addAttribute("state", 0);
        if (Objects.nonNull(result) && result.get("state").equals(0)) {
            resultMap.addAttribute("state", 1);
            Object respBody = result.get("content");
            if (Objects.nonNull(respBody)) {
                ModelMap modelMap = new ObjectMapper()
                        .convertValue(respBody, ModelMap.class);
                resultMap.addAllAttributes(modelMap);
                resultMap.put("companyId", modelMap.get("userId"));
                resultMap.put("accessToken", modelMap.get("utoken"));
            }
        }
        return resultMap;
    }

    /**
     * Http获取云盒列表
     *
     * @param boxHost
     * @param userId
     * @param token
     * @return
     */
    public static ModelMap getBoxListFromCloudPlatform(String boxHost, String userId, String token) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("x-cid", userId);
        httpHeaders.add("x-token", token);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<ModelMap> request = null;
        try {
            request = restTemplate.exchange(boxHost + "/eapi/box/list", GET, requestEntity, ModelMap.class);
            return request.getBody();
        } catch (ResourceAccessException | HttpServerErrorException e) {
            log.error("服务端或已关闭，拒绝连接...");
        } catch (RestClientException | IllegalArgumentException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Http获取云盒列表
     *
     * @param boxHost
     * @param userId
     * @param utoken
     * @return
     */
    public static ModelMap getBoxLiveVideoUrl(String boxHost, String userId, String utoken, String boxSn) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("x-cid", userId);
        httpHeaders.add("x-token", utoken);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<ModelMap> request = restTemplate.exchange(boxHost + "/eapi/box/liveUrl/" + boxSn, GET, requestEntity, ModelMap.class);
        return request.getBody();
    }

    public static ModelMap getTaskInfoFromCloudPlatform(String boxHost, String userId, String utoken, int taskId) {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("x-cid", userId);
        httpHeaders.add("x-token", utoken);
        HttpEntity<String> requestEntity = new HttpEntity<>(null, httpHeaders);
        RestTemplate restTemplate = new RestTemplate();
        ModelMap resultMap = null;
        try {
            ResponseEntity<ModelMap> request = restTemplate.exchange(boxHost + "/eapi/box/history/" + taskId, GET, requestEntity, ModelMap.class);
            ModelMap result = request.getBody();
            resultMap = new ModelMap();
            resultMap.addAttribute("state", 0);
            if (result != null && result.get("state").equals(0)) {
                resultMap.addAttribute("state", 1);
                Object respBody = result.get("content");
                if (Objects.nonNull(respBody)) {
                    ModelMap modelMap = new ObjectMapper()
                            .convertValue(respBody, ModelMap.class);
                    resultMap.addAllAttributes(modelMap);
                }
            }
        } catch (ResourceAccessException e) {
            log.error("服务端或已关闭，拒绝连接...");
        } catch (RestClientException | IllegalArgumentException e) {
            e.printStackTrace();
        }
        return resultMap;
    }
}